<!-- /src/views/order/OrderList.vue (完整替换) -->

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserOrders, payOrder, cancelOrder } from '@/api/order.js';

// --- 状态定义 ---
const orderList = ref([]);
const isLoading = ref(false);

const payDialogVisible = ref(false);
const paymentPin = ref('');
const currentPayingOrder = ref(null);
const isPaying = ref(false);

const statusMap = {
  0: { text: '未支付', type: 'warning' },
  1: { text: '已支付', type: 'success' },
  2: { text: '已取消', type: 'info' },
  3: { text: '系统原因取消', type: 'danger' }
};

// --- API 调用 ---

const fetchOrders = async () => {
  isLoading.value = true;
  try {
    const res = await getUserOrders();
    orderList.value = res.data;
  } catch (error) {
    ElMessage.error('获取订单列表失败');
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

const handlePay = (order) => {
  currentPayingOrder.value = order;
  paymentPin.value = '';
  payDialogVisible.value = true;
};

const submitPayment = async () => {
  if (!paymentPin.value) {
    ElMessage.warning('请输入支付密码');
    return;
  }
  isPaying.value = true;
  try {
    await payOrder({
      orderId: currentPayingOrder.value.orderId,
      pin: paymentPin.value
    });
    ElMessage.success('支付成功！');
    payDialogVisible.value = false;
    fetchOrders(); // 刷新列表
  } catch (error) {
    ElMessage.error(error.message || '支付失败，密码错误或余额不足');
    console.error(error);
  } finally {
    isPaying.value = false;
  }
};

const handleCancel = (order) => {
  ElMessageBox.confirm(
      `确定要取消订单【${order.orderId}】吗？`,
      '取消确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await cancelOrder(order.orderId);
      ElMessage.success('订单已取消');
      fetchOrders(); // 刷新列表
    } catch (error) {
      ElMessage.error(error.message || '取消失败');
      console.error(error);
    }
  });
};

onMounted(() => {
  fetchOrders();
});
</script>

<template>
  <div class="order-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的订单</span>
        </div>
      </template>

      <el-table :data="orderList" v-loading="isLoading" stripe>
        <el-table-column prop="orderId" label="订单号" width="180" />
        <el-table-column prop="productName" label="商品名称" show-overflow-tooltip/>
        <el-table-column prop="totalPrice" label="订单总价" width="120">
          <template #default="scope">
            <span>¥ {{ scope.row.totalPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="status" label="订单状态" width="150">
          <template #default="scope">
            <!-- 这里的 statusMap 会自动匹配我们新的定义 -->
            <el-tag :type="statusMap[scope.row.status]?.type || 'info'">
              {{ statusMap[scope.row.status]?.text || '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <!-- 只有"待支付"(status=0)的订单才能进行操作 -->
            <div v-if="scope.row.status === 0">
              <el-button type="primary" size="small" @click="handlePay(scope.row)">支付</el-button>
              <el-button type="danger" size="small" @click="handleCancel(scope.row)">取消订单</el-button>
            </div>
            <!-- 其他状态的订单不显示任何操作按钮 -->
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 支付弹窗 -->
    <el-dialog v-model="payDialogVisible" title="输入支付密码" width="300px" append-to-body>
      <el-input v-model="paymentPin" type="password" placeholder="请输入6位支付密码" show-password @keyup.enter="submitPayment" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPayment" :loading="isPaying">确认支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-list-container {
  padding: 20px;
}
</style>